package com.tanhua.manage.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.tanhua.manage.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /*获取验证码图片*/
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        //通知浏览器不要缓存数据！并告诉浏览器输出内容的类型
        //1、设置响应头
        response.setDateHeader("Expires",0);
        //Set standard HTTP/1.1 no-cache headers
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        //Set IE extended HTTP/1.1 no-cache header (user addHeader)
        response.addHeader("Cache-Cotrol","post-check=0,pre-check=0");
        //Set standard HTTP/1.0 no-cache header
        response.setHeader("Pragma","no-cache");
        //响应数据格式
        response.setContentType("image/jpeg");
        //2、调用hutool工具类，生成验证码图片
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(299,97);
        //3、获取验证码文字
        String code = circleCaptcha.getCode();
        //4、存入redis
        adminService.saveCap(uuid,code);
        //5、写入响应流
        circleCaptcha.write(response.getOutputStream());
    }

    /*登陆验证*/
    @PostMapping("/login")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> params){
        String username = params.get("username");
        String password = params.get("password");
        String verificationCode = params.get("verificationCode");
        String uuid = params.get("uuid");
        return adminService.login(username,password,verificationCode,uuid);
    }

    /*用户基本信息*/
    @PostMapping("/profile")
    public ResponseEntity<Object> profile(){
        return adminService.showPrefile();
    }

    /*用户退出*/
    @PostMapping("/logout")
    public ResponseEntity<Object> logout(@RequestHeader("Authorization")String token){
        return adminService.logout(token);
    }
}
